import React from 'react'
import {
  View,
  Text,
  SectionList,
  TouchableOpacity,
} from 'react-native'
import _ from 'lodash'

import { observer } from 'mobx-react-lite'

import Spinner from 'react-native-spinkit'

import { useStores } from '../stores'
import { useLayoutEffect } from 'react'
import { Spacer } from '../views'

const expandEpisode = chapters => {
  chapters = _.sortBy(chapters, it => it.index)
  const result = []

  const includes = episode => {
    for (let r of result) {
      if (_.includes(r, episode)) return true
    }
    return false
  }
  for (let chapter of chapters) {
    if (!includes(chapter.episode)) {
      result.push({ title: chapter.episode, data: [], info: {} })
    }
    if (chapter.title == chapter.episode) {
      result[result.length - 1].info = chapter
    } else {
      result[result.length - 1].data.push(chapter)
    }

  }
  return result
}

const ChaptersPlaceHolder = observer(({ count = 0 }) => {
  const { appearance: ap } = useStores()
  return (
    <View style={{ justifyContent: 'center', flex: 1, alignItems: 'center', backgroundColor: ap.theme.background }}>
      <Spinner color={ap.theme.primary} size={50} type={'Circle'} />
    </View>
  )
})

const ChapterItem = observer(({ chapter }) => {
  const { appearance: ap } = useStores()
  return (
    <TouchableOpacity style={{ ...styles.chapterItem }}>
      <Text style={{ ...styles.chapterTxt, color: ap.theme.second }}>{chapter.title}</Text>
    </TouchableOpacity>
  )
})

const EpisodeItem = observer(({ section }) => {
  const { appearance: ap } = useStores()

  if (section.info.content) {
    return (
      <TouchableOpacity style={{ ...styles.episodeItem, backgroundColor: ap.theme.background }}>
        <Text style={{ ...styles.episodeTxt }}>{section.title}</Text>
      </TouchableOpacity>
    )
  }
  return (
    <View style={{ ...styles.episodeItem, backgroundColor: ap.theme.background }}>
      <Text style={{ ...styles.episodeTxt }}>{section.title}</Text>
    </View>
  )
})

export default observer(({ navigation, route }) => {
  const { appearance: ap, bookApi } = useStores()
  const [chapters, setChapters] = React.useState()
  const { book } = route.params
  useLayoutEffect(() => {
    navigation.setOptions({
      title: book.name
    })
  })
  if (!chapters) {
    console.log(book._id)
    bookApi.fetchChapters(book._id).then(data => {
      setChapters(expandEpisode(data.chapters))
    })
    return <ChaptersPlaceHolder />
  }
  return (
    <SectionList
      style={{ ...styles.container, backgroundColor: ap.theme.background }}
      sections={chapters}
      renderItem={({ item }) => <ChapterItem chapter={item} />}
      renderSectionHeader={({ section }) => <EpisodeItem section={section} />}
      keyExtractor={(it, i) => `${it._id}-${i}`}
      renderSectionFooter={({ section }) => <View style={{ paddingBottom: 25 }} />}
      stickySectionHeadersEnabled={false}
    />
  )
})

const styles = {
  container: {
    flex: 1,
    paddingBottom: 30,
  },

  container: {
    flex: 1,
    padding: 12,
  },

  chapterItem: {
    // alignItems: 'center'
  },

  episodeItem: {
    // alignItems: 'center'
  },

  episodeTxt: {
    fontSize: 16,
    fontWeight: 'bold',
  },

  chapterTxt: {
    fontSize: 14,
    paddingBottom: 3,
    paddingTop: 3,
  }
}